package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;

import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class BannerServiceImpl implements IBannerService {


    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        //查询对象
        Query query = new Query();
        //查询总条数
        long totalCount = mongoTemplate.count(query, Banner.class);

        //使用PageRequest.of方法
        //第一个参数：当前页（从0开始算第一页）
        //第二个参数：每页显示的条数
        //第三个参数：排序规则
        //第四个参数：排序字段
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        query.with(pageable);
        List<Banner> Banners = mongoTemplate.find(query, Banner.class);
        return new PageImpl(Banners,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if(StringUtils.hasLength(banner.getId())){
            this.update(banner);
        }else {
            this.save(banner);
        }
    }

    @Override
    public List<Banner> queryByTravel(int type) {
      Pageable pageable = PageRequest.of(0,5,Sort.Direction.DESC,"sequence");
        List<Banner> banners = bannerRepository.findByStateAndType(Banner.STATE_NORMAL, type, pageable);
        return banners;
    }

    @Override
    public Banner queryByStrategy(int type) {

        Pageable pageable = PageRequest.of(0,5,Sort.Direction.DESC,"sequence");
        List<Banner> bannersList = bannerRepository.findByStateAndType(Banner.STATE_NORMAL, type, pageable);
        return bannersList.get(0);
    }


}
